package com.lfg.leetcode.leetcode200;

public class No214shortestPalindrome {

    public static void main(String[] args) {
        String ret = shortestPalindrome("abcd");
        System.out.println(ret);
    }

    public static String shortestPalindrome(String s) {
        if (null == s) {
            return s;
        }
        int length = s.length();
        char[] array = s.toCharArray();
        StringBuilder sb = new StringBuilder(2 * length);
        int i = length - 1;
        for (; i >= 0; i--) {
            if (array[0] == array[i] && testPalindrome(array, 1, i - 1)) {
                break;
            }
        }
        for (int index = length - 1; index > i; index--) {
            sb.append(array[index]);
        }
        sb.append(s);
        return sb.toString();
    }

    public static boolean testPalindrome(char[] array, int low, int high) {
        while (low < high) {
            if (array[low++] != array[high--]) {
                return false;
            }
        }
        return true;
    }

}
